
<template>
  <div class="body">
    <el-form :rules="rules" ref="loginForm" :model="loginForm" class="loginContainer">
      <h3 class="loginTitle">
        登录
      </h3>
      <p class="welcomeMessage" align="center">欢迎访问智慧社区管理平台</p>
      <el-form-item prop="username">
        <el-input type="text" v-model="loginForm.username" placeholder="请输入用户名" >
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" >
        </el-input>
      </el-form-item>

      <el-form-item prop="code">
        <!-- 使用div包裹el-input和img，作为Flex容器 -->
        <div style="display: flex; align-items: center;">
          <el-input
              type="text"
              auto-complete="false"
              v-model="loginForm.code"
              placeholder="点击图片更换验证码"
              style="margin-right: 5px;"
          >
          </el-input>
          <!-- 移除了style中的width属性，因为Flex布局会处理宽度 -->
          <img :src="captchaUrl" @click="getCaptcha" alt="验证码" title="点击刷新验证码" style="width: 100px; height: 40px; cursor: pointer;">
        </div>
      </el-form-item>

      <el-button type="primary" style="width:100%" @click="submitLogin">登录</el-button>
    </el-form>
  </div>
</template>

<script>

import http from '@/utils/http';
import { checkToken } from '@/router/index';
import Utils from "@/store/util"; // 导入checkToken函数

export default {
  name: "login",
  data(){
    return{
      captchaUrl: "",
      captchaId: "",
      loginForm:{
        username:"vipadmin",
        password:"qwe123",
        code: ""
      },
      checked: true,
      rules:{
        username:[{required:true,message:"请输入用户名",trigger:"blur"},{ min: 5, max: 14, message: '长度在 5 到 14 个字符', trigger: 'blur' }
        ],
        password:[{required:true,message:"请输入密码",trigger:"blur"},{ min: 6,  message: '密码长度要大于6', trigger: 'blur' }],
        code:[{required:true,message:"请输入验证码",trigger:"blur"}],
      }
    }
  },
  created() {
    if (checkToken()) {
      this.$router.push('/');
    } else {
      // 组件创建时立即获取验证码
      this.getCaptcha();
    }
  },

  methods:{
    submitLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // alert('登录成功');
          http.get("/admin/noRole/login", {
            params: {
              name: this.loginForm.username,
              password: this.loginForm.password,
              captchaId: this.captchaId,
              inputCaptcha: this.loginForm.code
            }
          })
              .then(response => {
                // 请求成功，处理响应数据
                console.log(response);
                const Result = response.data;
                // 登录成功
                if (Result.success) {
                  this.$message.success("登录成功！")
                  // 保存Token到localStorage
                  console.log('userToken:' + Result.data);
                  localStorage.setItem('userToken', Result.data);

                  // 调用后端接口获取权限后保存到localStorage
                  http.get('/admin/noRole/getMyType').then(permResponse => {
                    if (permResponse.data.success) {
                      console.log('adminPermissions:', permResponse.data.data);
                      localStorage.setItem('adminPermissions', JSON.stringify(permResponse.data.data));
                      Utils.$emit('refreshMenu','msg');
                    } else {
                      this.$message.error(permResponse.data.errorMsg);
                    }
                  });
                  // 重定向到首页或其他页面
                  this.$router.push('/');

                } else {
                  // 登录失败
                  this.$message.error(Result.errorMsg);
                  this.getCaptcha(); // 确保getCaptcha可以刷新验证码
                }
              })
              .catch(function (error) {
                // 请求失败，处理错误情况
                console.error(error);
                this.getCaptcha();
              });
        } else {
          this.$message.error('数据格式有误，请重新输入！');
          return false;
        }
      });

    },
    //获取图片验证码
    getCaptcha() {
      http.get("/captcha/captchaImage")
          .then((response) => {
            this.responseResult = response.data;
            this.captcha64 = this.responseResult.data.captchaImage;
            this.captchaId = this.responseResult.data.captchaId; // 更新captchaId值

            this.captchaImage = atob(this.captcha64);
            const uint8Array = new Uint8Array(this.captchaImage.length);
            for (let i = 0; i < this.captchaImage.length; i++) {
              uint8Array[i] = this.captchaImage.charCodeAt(i);
            }//解码base64图片

            const blob = new Blob([uint8Array], { type: 'image/jpeg' }); // 根据实际图片类型设置type
            this.captchaUrl = URL.createObjectURL(blob); //设置验证码图片链接
          })
          .catch(error => {
            this.$message('生成图片验证码失败');
            if (error.response) {
              // 请求已发送，但服务器返回非 2xx 响应
              console.log('响应状态码：', error.response.status);
              console.log('响应数据：', error.response.data);
            } else if (error.request) {
              // 请求已发送，但没有收到响应
              console.log('无响应：', error.request);
            } else {
              // 发生了其他错误
              console.log('错误消息：', error.message);
            }
          })
    },
  }
};
</script>

<style lang="scss" scoped>
$login-container-width: 350px;
$login-container-height: 350px; // 可以根据实际高度调整

.loginContainer {
  border-radius: 15px;
  background-clip: padding-box;
  text-align: left;
  margin: auto;
  margin-top: 180px; // 可以根据实际位置调整
  width: $login-container-width;
  padding: 15px 35px;
  background: aliceblue;
  border: 1px solid rgba(43, 73, 226, 0.63);
  box-shadow: 0 0 25px #ffffff;
  display: flex;
  flex-direction: column;
  justify-content: center; // 垂直居中
}

.loginTitle {
  margin: 0 auto 0px auto;
  text-align: center;
  font-size: 40px;
}

.loginRemember {
  text-align: left;
  margin: 0 0 15px 0;
}

/* 确保html和body占满整个视口 */
html, body {
  width: 100%;
  height: 100%;
  margin: 0; /* 移除默认的边距 */
  padding: 0; /* 移除默认的内边距 */
  overflow: hidden; /* 防止滚动条出现 */
}

/* 设置flex容器 */
.body {
  display: flex; /* 启用flex布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  position: absolute; /* 绝对定位，相对于整个视口 */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url("../assets/background.jpg"); /* 设置背景图片 */
  background-position: center; /* 背景图片居中显示 */
  background-repeat: no-repeat; /* 背景图片不重复 */
  background-size: cover; /* 背景图片覆盖整个元素 */
}


</style>